package live.ifox.stage;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import live.ifox.base.BaseRestActivity;
import live.ifox.factory.Entry;
import live.ifox.factory.ID;
import live.ifox.factory.Url;
import live.ifox.helper.AdapterHelper;
import live.ifox.helper.CommonHelper;

public class JournalEditor extends BaseRestActivity {
    boolean updateFlag, scanFlag;
    Spinner spinner;
    List<String> categories;
    EditText et_category, et_detail;
    int _id;
    String _category, _detail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.parlor_editor);
        actionBar.setTitle(R.string.journal);

        entry = Entry.Journal;
        baseUrl = Url.Journal;
        scanFlag = checkPermission();
        spinner = findViewById(R.id.providers);
        et_category = findViewById(R.id.category);
        et_detail = findViewById(R.id.detail);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                et_category.setText(categories.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        _id = getIntent().getIntExtra("id", 0);
        if (_id > 0) {
            updateFlag = true;
            _category = getIntent().getStringExtra("category");
            _detail = getIntent().getStringExtra("detail");
            et_detail.setText(_detail);
        }
        updateCategory();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID.CODE_SCANNER, 0, "扫码...");
        return true;
    }

    void updateCategory() {
        httpGet(baseUrl + "get_categories");
    }

    boolean checkPermission() {
        int permission = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA);

        return permission == PackageManager.PERMISSION_GRANTED;
    }

    void requestPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA}, ID.CODE_SCANNER);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ID.CODE_SCANNER) {
            int grantResult = grantResults[0];
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                scanFlag = false;
                CommonHelper.showMessage(this, "您拒绝了程序运行所需要的权限！");
            } else {
                scanFlag = true;
                startActivityForResult(new Intent(this,
                        CodeScanner.class), ID.CODE_SCANNER);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case ID.CODE_SCANNER:
                if (scanFlag) {
                    startActivityForResult(new Intent(this,
                            CodeScanner.class), ID.CODE_SCANNER);
                    return true;
                } else {
                    requestPermission();
                    return false;
                }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void processReply(JSONObject rootObject) {
        JSONArray array = AdapterHelper.verifyObject(rootObject,
                "entry", entry, "categories");
        if (array.isEmpty())
            return;

        categories = array.toJavaList(String.class);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_dropdown_item);
        adapter.addAll(categories);
        spinner.setAdapter(adapter);
        if (updateFlag) {
            if (categories.contains(_category))
                spinner.setSelection(categories.indexOf(_category));
        }
    }

    public void onClean_Click(View view) {
        if (!et_category.getText().toString().isEmpty())
            et_category.setText("");

        if (!et_detail.getText().toString().isEmpty())
            et_detail.setText("");
    }

    public void onSubmit_Click(View view) {
        String category = et_category.getText().toString();
        if (category.isEmpty())
            category = "事务";

        String detail = et_detail.getText().toString();
        if (detail.isEmpty()) {
            CommonHelper.showMessage(this, "内容不能为空！");
            return;
        }

        Map<String, Object> map = new HashMap<>();
        if (!updateFlag) {
            map.put("category", category);
            map.put("detail", detail);
            httpPost(baseUrl + "insert", JSON.toJSONString(map));
        } else {
            if (!_category.equals(category))
                map.put("category", category);

            if (!_detail.equals(detail))
                map.put("detail", detail);

            if (map.isEmpty())
                return;

            map.put("id", _id);
            httpPost(baseUrl + "update", JSON.toJSONString(map));
        }
        setResult(ID.RESULT_DONE);
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;

        if (resultCode == ID.RESULT_DONE && requestCode == ID.CODE_SCANNER) {
            String code = data.getStringExtra("code");
            if (code.isEmpty())
                return;

            et_detail.append(code);
        }
    }
}